<template>
  <div class="api-interface">
    <div class="upload-section">
      <a-upload
        :file-list="fileList"
        :before-upload="beforeUpload"
        :show-upload-list="false"
        multiple
        accept="image/*"
      >
        <a-button type="primary" :loading="uploading">
          <upload-outlined /> 上传素材
        </a-button>
      </a-upload>
    </div>

    <div class="materials-list">
      <div class="list-header">
        <h3>我的素材</h3>
        <a-button size="small" @click="loadMaterials">刷新</a-button>
      </div>

      <div class="materials-grid">
        <div v-for="item in materials" :key="item.id" class="material-item">
          <div class="material-preview">
            <img :src="item.url" :alt="item.name" />
          </div>
          <div class="material-info">
            <div class="material-name">{{ item.name }}</div>
            <div class="material-actions">
              <a-button
                type="primary"
                size="small"
                @click.stop="addToCanvas(item)"
                >添加到画布</a-button
              >
              <a-button
                type="error"
                size="small"
                @click.stop="deleteMaterial(item.id)"
                >删除</a-button
              >
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, inject } from 'vue'
import { message } from 'ant-design-vue'
import { UploadOutlined } from '@ant-design/icons-vue'
import { fabric } from 'fabric'
import type { Editor } from '@kuaitu/core'
import {
  uploadMaterial,
  saveMaterialInfo,
  deleteMaterialInfo,
  getUserMaterials,
} from '@/api/material'

interface MaterialItem {
  id: string
  name: string
  url: string
  type: string
  size: number
  uploadTime: number
}

// 获取画布编辑器实例
const canvasEditor = inject<Editor>('canvasEditor')

// 响应式数据
const fileList = ref([])
const uploading = ref(false)
const materials = ref<MaterialItem[]>([])

// 支持的文件类型
const allowedTypes = [
  'image/jpeg',
  'image/jpg',
  'image/png',
  'image/gif',
  'image/webp',
  'image/svg+xml',
]

// 文件上传前的处理
const beforeUpload = async (file: File) => {
  // 检查文件类型
  if (!allowedTypes.includes(file.type)) {
    message.error('只支持图片格式文件！')
    return false
  }

  // 检查文件大小 (10MB)
  if (file.size > 10 * 1024 * 1024) {
    message.error('文件大小不能超过 10MB！')
    return false
  }

  try {
    uploading.value = true

    // 上传文件到服务器
    const uploadResult = await uploadMaterial(file)

    // 保存素材信息到数据库
    const materialInfo = {
      name: file.name,
      url: uploadResult.url,
      type: file.type,
      size: file.size,
    }

    const savedMaterial = await saveMaterialInfo(materialInfo)

    // 添加到本地列表
    const newMaterial: MaterialItem = {
      id: savedMaterial.id,
      name: file.name,
      url: uploadResult.url,
      type: file.type,
      size: file.size,
      uploadTime: Date.now(),
    }

    materials.value.unshift(newMaterial)

    // 更新本地存储
    localStorage.setItem('userMaterials', JSON.stringify(materials.value))

    message.success('素材上传成功！')
  } catch (error) {
    console.error('上传失败:', error)
    message.error('上传失败，请重试！')
  } finally {
    uploading.value = false
  }

  return false // 阻止默认上传行为
}

// 添加素材到画布
const addToCanvas = (item: MaterialItem) => {
  if (!canvasEditor) {
    message.error('画布编辑器未初始化！')
    return
  }

  // 创建图片对象并添加到画布
  fabric.Image.fromURL(item.url, (img) => {
    // 设置图片属性
    img.set({
      left: 100,
      top: 100,
      scaleX: 0.5,
      scaleY: 0.5,
    })

    // 添加到画布
    canvasEditor.canvas.add(img)
    canvasEditor.canvas.renderAll()

    message.success('素材已添加到画布！')
  })
}

// 删除素材
const deleteMaterial = async (id: string) => {
  try {
    await deleteMaterialInfo(id)

    // 从本地列表中移除
    materials.value = materials.value.filter((item) => item.id !== id)

    // 更新本地存储
    localStorage.setItem('userMaterials', JSON.stringify(materials.value))

    message.success('素材删除成功！')
  } catch (error) {
    console.error('删除失败:', error)
    message.error('删除失败，请重试！')
  }
}

// 加载素材列表
const loadMaterials = async () => {
  try {
    const result = await getUserMaterials()
    materials.value = result.map((item: any) => ({
      id: item.id,
      name: item.name,
      url: item.url,
      type: item.type,
      size: item.size,
      uploadTime: item.uploadTime || Date.now(),
    }))

    // 更新本地存储
    localStorage.setItem('userMaterials', JSON.stringify(materials.value))
  } catch (error) {
    console.error('加载素材失败:', error)
    // 如果服务器加载失败，从本地存储加载
    const localMaterials = localStorage.getItem('userMaterials')
    if (localMaterials) {
      materials.value = JSON.parse(localMaterials)
    }
  }
}

// 组件挂载时加载素材
onMounted(() => {
  loadMaterials()
})
</script>

<style lang="less" scoped>
.api-interface {
  padding: 20px 0;
  height: 100%;
  overflow-y: auto;
}

.header {
  margin-bottom: 20px;
  
  h3 {
    margin: 0 0 8px 0;
    font-size: 16px;
    font-weight: 600;
    color: #333;
  }
  
  .desc {
    margin: 0;
    font-size: 12px;
    color: #999;
  }
}

.upload-section {
  margin-bottom: 30px;
  
  .upload-area {
    padding: 40px 20px;
    text-align: center;
    border: 2px dashed #d7dde4;
    border-radius: 6px;
    background: #fafafa;
    transition: all 0.3s;
    
    &:hover {
      border-color: #3399ff;
      background: #f0f8ff;
    }
    
    p {
      margin: 10px 0 0 0;
      font-size: 14px;
      color: #666;
      
      &.upload-tips {
        font-size: 12px;
        color: #999;
      }
    }
  }
  
  .progress-section {
    margin-top: 15px;
  }
}

.history-section {
  h4 {
    margin: 0 0 15px 0;
    font-size: 14px;
    font-weight: 600;
    color: #333;
  }
  
  .material-list {
    .material-item {
      display: flex;
      align-items: center;
      padding: 12px;
      margin-bottom: 10px;
      border: 1px solid #e8eaec;
      border-radius: 6px;
      cursor: pointer;
      transition: all 0.3s;
      
      &:hover {
        border-color: #3399ff;
        box-shadow: 0 2px 8px rgba(51, 153, 255, 0.1);
      }
      
      .material-preview {
        width: 50px;
        height: 50px;
        margin-right: 12px;
        border-radius: 4px;
        overflow: hidden;
        background: #f5f5f5;
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
      
      .material-info {
        flex: 1;
        
        .material-name {
          margin: 0 0 4px 0;
          font-size: 13px;
          color: #333;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        .material-time {
          margin: 0;
          font-size: 11px;
          color: #999;
        }
      }
      
      .material-actions {
        display: flex;
        gap: 8px;
        
        .ivu-btn {
          padding: 4px 8px;
          font-size: 11px;
        }
      }
    }
  }
  
  .empty-state {
    text-align: center;
    padding: 40px 20px;
    color: #999;
    
    p {
      margin: 10px 0 0 0;
      font-size: 13px;
    }
  }
}
</style>